<?php

/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2020/5/22
 * Time: 14:47
 */

namespace App\Http\Controllers\PayInfo;

use App\Http\Controllers\PayInfo\WechatPayController;
use App\Models\BookHomeOrder;
use App\Models\BookHomeOrderPay;
use App\Models\LibBook;
use App\Models\LibBookBarcode;
use App\Models\ShopBook;
use App\Models\UserLibraryInfo;
use App\Models\UserWechatInfo;
use App\Validate\BookHomePayInfoValidate;
use Illuminate\Support\Facades\DB;

/**
 * 支付模块
 * Class PayInfo
 * @package app\port\controller
 */
class BookHomePayInfoController extends CommonController
{

    public $model = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new BookHomeOrder();
        $this->validate = new BookHomePayInfoValidate();
    }


    /**
     * 统一下单，获取支付所需的参数
     * @param order_id  订单id
     */
    public function getPayInfo()
    {
        return $this->returnApi(202, '演示项目不支持在线支付！');
        // 自动验证
        if (!$this->validate->scene('get_pay_param')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $user_id = $this->request->user_info['id'];
        $wechat_id = $this->request->user_info['wechat_id'];
        $order_id = $this->request->order_id;
        //直接修改状态
        $order_info = $this->model->find($order_id);

        if (empty($order_info)) {
            return $this->returnApi(203, '网络错误');
        }
        if ($order_info['is_pay'] != 1) {
            return $this->returnApi(203, '网络错误');
        }
        //判断读者证号密码是否正确
        $userLibraryInfoModel = new UserLibraryInfo();
        $account_lib_info = $userLibraryInfoModel->checkAccountPwdIsNormal($user_id);
        if (is_string($account_lib_info)) {
            return $this->returnApi(204, $account_lib_info);
        }

        //再次检查读者证号状态  判断读者证号密码是否正确
        $shopBookModel = new ShopBook();
        try {
            $book_ids = $this->model->where('order_id', $order_id)->pluck('book_id');
            //判断用户借阅权限
            if ($order_info->type == 1) {
                //新书需要多判断一些记录
                $shopBookModel->checkNewBookBorrowAuth($order_info['account_id'], $book_ids, false, true);
            } else {
                $barcode_ids = $this->model->where('order_id', $order_id)->pluck('barcode_id');
                $barcodes = LibBookBarcode::select('barcode')->whereIn('id', $barcode_ids)->get();

                //判断是否在借阅流程中
                $libBookModel = new LibBook();
                //在判断图书馆借阅权限
                $libBookModel->checkNewBookBorrowAuth($account_info, $barcodes, false, true);
            }
        } catch (\Exception $e) {
            return $this->returnApi(202, $e->getMessage());
        }

        $open_id = UserWechatInfo::where('id', $wechat_id)->value('open_id');
        $price = (int)($order_info->price * 100); //支付金额转换为分
        $wechatPayObj = new WechatPayController($order_info->order_number, '书籍借阅邮费支付', $price, $open_id);
        $res = $wechatPayObj->pay();

        if ($res) {
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(202, '获取失败');
    }


    /**
     * 支付成功,验证订单状态，验证成功后修改订单状态
     * @param order_id  订单id
     */
    public function paymentSuccess()
    {
        // 自动验证
        if (!$this->validate->scene('payment_success')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $order_id = $this->request->order_id;
        //直接修改状态
        $order_info = $this->model->find($order_id);
        if (empty($order_info)) {
            return $this->returnApi(203, '网络错误');
        }

        if ($order_info['is_pay'] == 1) {
            //自助验证状态
            $result = $this->checkWeChatPay($order_id);

            if (!$result) {
                return $this->returnApi(202, '支付失败');
            }
            return $this->returnApi(200, '支付成功', true);
        } elseif ($order_info['is_pay'] == 2) {
            return $this->returnApi(200, '支付成功', true);
        }

        return $this->returnApi(202, '支付失败');
    }

    /**
     * 修改书袋书籍状态并推送
     */
    public function modifySchoolbagState($order_info)
    {
        //添加系统消息
        $type = $order_info['type'] == 1 ? 36 : 37;
        $this->systemAdd('书籍采购提交成功', $order_info['user_id'], $order_info['account_id'], $type, $order_info['id'], '书籍采购提交成功，等待后台管理员审核，请随时关注审核进度！');
    }

    /**
     * 查询微信支付系统
     */
    public function checkWeChatPay($order_id)
    {
        $order_info = $this->model->find($order_id);
        if ($order_info->is_pay == 2) {
            return true; //已支付成功
        }

        //调用微信查询接口
        $wechatPayObj = new WechatPayController($order_info->order_number);
        $result = $wechatPayObj->checkWxOrderPay();

        if (!$result) {
            return false;
            //return $this->returnData(203 , '数据异常');//实际为未查询到支付交易情况
        }
        //否则提交信息，修改数据
        //返回的$result为数组

        //微信支付订单号
        $trade_no = $result['transaction_id'];
        //订单支付时间
        $time_end = $result['time_end'];
        //转换为时间戳
        $gtime = strtotime($time_end);
        $gmt_payment = date("Y-m-d H:i:s", $gtime); //转换为日期时间格式
        //买家微信支付分配的终端设备号，
        //   $buyer_id  = $result['device_info'];
        //买家微信账号
        //	$buyer_login_id  = $_POST['buyer_login_id'];
        //订单总金额,订单总金额，单位为分
        $total_amount = $result['total_fee'];
        //实收金额,商家在交易中实际收到的款项
        $receipt_amount = $result['total_fee']; //微信的实收与总金额一致
        //付款金额,现金支付金额订单现金支付金额，详见支付金额
        $buyer_pay_amount = $result['cash_fee'];

        //此处编写回调处理逻辑
        $where = array(
            'order_number' => $order_info->order_number,
            'pay_time' => $gmt_payment,
            'payment' => 1,
            'trade_no' => $trade_no,
            //    'buyer_id'		=> $buyer_id,
            //	'buyer_login_id'=>$buyer_login_id,
            'total_amount' => $total_amount,
            'receipt_amount' => $receipt_amount,
            'buyer_pay_amount' => $buyer_pay_amount,
        );

        //开启事务
        DB::beginTransaction();
        try {
            $this->model->where('id', $order_id)->update(['is_pay' => 2, 'change_time' => $gmt_payment]);
            $bookHomdeOrderPayModel = new BookHomeOrderPay();
            $bookHomdeOrderPayModel->add($where);

            //添加推送信息
            $this->modifySchoolbagState($order_info);
            DB::commit();
            return true;    //支付成功
        } catch (\Exception $e) {
            DB::rollBack();
            return false;
        }
    }
}
